<?php
require_once("config.php");
require_once("utils.php");

date_default_timezone_set(getConfig($config, 'timezone', FALSE, 'Europe/Amsterdam'));

require_once("ext/smarty/libs/Smarty.class.php");
$smarty = new Smarty();
$smarty->template_dir = 'tpl';
$smarty->compile_dir = 'tpl_c';

$people = array();

$show_score = getConfig($config, 'score_show_value', FALSE, TRUE);

$conn = mysql_connect(getConfig($config, 'db_host', TRUE), getConfig($config, 'db_user', TRUE), getConfig($config, 'db_pass', TRUE));
if (!$conn)
	throw new Exception("Unable to connect to DB: " . mysql_error());
if (!mysql_select_db(getConfig($config, 'db_name', TRUE)))
	throw new Exception("Unable to select database: " . mysql_error());

$limit = getConfig($config, 'score_limit', FALSE, 9);

$sql = "SELECT u.name, COUNT(*) AS score
	FROM UserAnswer a, Question q, User u
	WHERE a.possibleAnswerID = q.correctAnswerID AND a.userID = u.id
	GROUP BY a.userID
	ORDER BY score DESC
	LIMIT $limit";

$result = mysql_query($sql);
if (!$result)
    throw new Exception("Could not successfully run query ($sql) from DB: " . mysql_error());

while ($row = mysql_fetch_assoc($result)) {
	$name = filter_var($row['name'], FILTER_SANITIZE_SPECIAL_CHARS);
	$score = filter_var($row['score'], FILTER_SANITIZE_SPECIAL_CHARS);

	if($show_score)
		$display = $name . " (" . $score . ")";
	else
		$display = $name;

	array_push($people, $display);
}
mysql_free_result($result);

$sql = "SELECT name
	FROM User
	ORDER BY RAND()";

$prtcpnts = array();

$result = mysql_query($sql);
if (!$result)
    throw new Exception("Could not successfully run query ($sql) from DB: " . mysql_error());

while ($row = mysql_fetch_assoc($result)) {
	array_push($prtcpnts, $row['name']);
}

$participants = implode(" :: ", $prtcpnts);

$smarty->assign('qruiz', $people);
$smarty->assign('name', getConfig($config,'quiz_name', FALSE, 'Demo'));
$smarty->assign('participants', $participants);
$smarty->assign('limit', $limit);
$smarty->assign('refresh_time', getConfig($config, 'score_refresh', FALSE, 60));

$smarty->display('score.tpl');
?>
